package com.linc.concurrency.barrier;

import java.util.Date;
import java.util.concurrent.Exchanger;

public class ExchangerDemo {
  private final Thread fillerThread;
  private final Thread consumerThread;
  private final Exchanger<String> exchanger = new Exchanger<>();

  public ExchangerDemo() {
    fillerThread = new Thread(new Filler());
    consumerThread =
        new Thread(
            () -> {
              while (true) {
                String buffer = String.valueOf(System.currentTimeMillis());
                try {
                  buffer = exchanger.exchange(buffer);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                System.out.println(this.getClass().getSimpleName() + " after exchange: " + buffer);
              }
            });
  }

  public void start() {
    fillerThread.start();
    consumerThread.start();
  }

  public static void main(String[] args) {
    new ExchangerDemo().start();
  }

  class Filler implements Runnable {
    @Override
    public void run() {
      while (true) {
        // 填充buffer
        String buffer = new Date().toString();
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        try {
          buffer = exchanger.exchange(buffer);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(this.getClass().getSimpleName() + " after exchange: " + buffer);
      }
    }
  }
}
